package com.erp.activity


import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.util.Log
import android.view.KeyEvent
import android.view.View
import android.widget.AdapterView
import androidx.appcompat.app.ActionBarDrawerToggle
import com.erp.Interface.OnUserDataInterface
import com.erp.Myapp
import com.erp.R
import com.erp.bean.DrawerBean
import com.erp.bean.MainItemBeans
import com.erp.contacts.Contacts
import com.erp.mclass.QuanXian
import com.erp.mclass.UpdataInfo
import com.erp.module.xieyi.XieyiActivity
import com.erp.myAdapter.MainItemAdapter
import com.erp.notifiactionDb.PersonDB
import com.erp.permission.PermissionListener
import com.erp.util.Httputil
import com.erp.util.JsonUtil
import com.erp.util.Myutil
import com.erp.util.PermissionUtils
import com.erp.view.MyAlerDialog
import com.taobao.sophix.SophixManager
import kotlinx.android.synthetic.main.activity_main.IvDownload
import kotlinx.android.synthetic.main.activity_main.IvNotification
import kotlinx.android.synthetic.main.activity_main.LlGengxing
import kotlinx.android.synthetic.main.activity_main.LlQuit
import kotlinx.android.synthetic.main.activity_main.Tv_Fuwu
import kotlinx.android.synthetic.main.activity_main.Tv_Yingsi
import kotlinx.android.synthetic.main.activity_new_main.*
import kotlinx.android.synthetic.main.activity_new_main.GvHomePage
import org.json.JSONException
import org.json.JSONObject
import java.util.*

/**
 * Created by Administrator on 2016/11/28/028.
 * 作者：刘洋
 * activit内嵌fragmengt，用于显示数据
 */
class NewMainKActivity : BaseActivity(), View.OnClickListener, AdapterView.OnItemClickListener {
    private val TAG = "MainActivity.class"
    var isdrawerLayout = false
    lateinit var listItems: MutableList<MainItemBeans.MainItemBean>
    /**
     * 广播接受着，用于在退出时关闭activity
     */
    private val mBoradcastReceiver = object : BroadcastReceiver() {
        override fun onReceive(context: Context, intent: Intent) {
            if (intent.action == Contacts.BORADCAST_ACTION_EXIT) {//关闭app的广播
                val personDB = PersonDB.getIntance()
                personDB.clear()
                finish()
            } else if (intent.action == Contacts.BORADCAST_ACTION_NOTI) {//收到通知的广播
                isnotification()
            } else if (intent.action == Contacts.BORADCAST_ACTION_UPDATE) {//更新的广播
                UpdataInfo(this@NewMainKActivity, false, sp).show()
            } else if (intent.action == Contacts.BORADCAST_ACTION_SOPHIX) {
                val activity = Myapp.list[Myapp.list.size - 1]
                val myAlerDialog = MyAlerDialog(activity)
                myAlerDialog.start()
                myAlerDialog.setdata("下载了新补丁需要重启应用，点击确定立即重启！")
                myAlerDialog.setleft("确定") { SophixManager.getInstance().killProcessSafely() }
                myAlerDialog.setright("取消") { myAlerDialog.getdialog().dismiss() }
                myAlerDialog.show()
            }
        }
    }

    override fun getLayoutId(): Int {
        activityname = a
        return R.layout.activity_new_main
    }

    override fun initCreate() {
        // 在当前的activity中注册广播
        val filter = IntentFilter()
        filter.addAction(Contacts.BORADCAST_ACTION_EXIT)//为BroadcastReceiver指定一个action，即要监听的消息名字
        filter.addAction(Contacts.BORADCAST_ACTION_NOTI)//为BroadcastReceiver指定一个action，即要监听的消息名字
        filter.addAction(Contacts.BORADCAST_ACTION_UPDATE)//为BroadcastReceiver指定一个action，即要监听的消息名字
        filter.addAction(Contacts.BORADCAST_ACTION_SOPHIX)//为BroadcastReceiver指定一个action，即要监听的消息名字
        registerReceiver(mBoradcastReceiver, filter) //动态注册监听  静态的话 在AndroidManifest.xml中定义

        initView()
        UpdataInfo(this, false, sp).show()
        tvTitle.isFocusable = true
        tvTitle.isFocusableInTouchMode = true
        tvTitle.requestFocus()
        tvTitle.requestFocusFromTouch()
        PermissionUtils.isupdate(this@NewMainKActivity, object : PermissionListener {
            override fun onSucceed(requestCode: Int, grantPermissions: List<String>) = Unit

            override fun onFailed(requestCode: Int, deniedPermissions: List<String>) = Unit
        })
        SophixManager.getInstance().queryAndLoadNewPatch()
    }

    private fun isnotification() {
        val personDB: PersonDB = PersonDB.getIntance()
        val notificationBeens = personDB.findfase(false)
        if (notificationBeens != null) {
            if (notificationBeens.size != 0) {
                ivTongzhi.visibility = View.VISIBLE
                IvNotification.setImageResource(R.mipmap.erp_message1)
            } else {
                ivTongzhi.visibility = View.GONE
                IvNotification.setImageResource(R.mipmap.erp_message)
            }
        }
    }

    private fun drawerLayout() {
        var mDrawerToggle = object : ActionBarDrawerToggle(this, DlLeft, iv_header_left, R.string.open, R.string.close) {
            override fun onDrawerOpened(drawerView: View) {
                isdrawerLayout = true
                super.onDrawerOpened(drawerView)

            }

            override fun onDrawerClosed(drawerView: View) {
                isdrawerLayout = false
                super.onDrawerClosed(drawerView)
            }
        }
        mDrawerToggle.syncState()
        DlLeft.addDrawerListener(mDrawerToggle)
        val user = sp.getString("user", "")
        Log.d("TAAG", "user=$user")
        val drawerBean = DrawerBean()
        val quanXian = QuanXian()
        try {
            val jo1 = JSONObject(user)
            uid = jo1.getString("uid")
            name = jo1.getString("name")
            editor.putString("uid", uid)
            drawerBean.mname = jo1.getString("name")
            drawerBean.youxiang = jo1.getString("mail")
            drawerBean.zhuceshijian = jo1.getString("created")
            drawerBean.denglushijian = jo1.getString("login")
            drawerBean.shangcidenglu = jo1.getString("access")
            val jo2 = jo1.getJSONObject("kerp")
            drawerBean.bieming = jo2.getString("alias_name")
            drawerBean.daoqishijian = jo2.getString("expire_time")
            ZhuanMaiDianid = JsonUtil.getvolue(jo2, "exclusive_shop")
            val jo3 = jo1.getJSONObject("permissions")
            quanXian.geuQuanXian(jo3)
        } catch (e: JSONException) {
            e.printStackTrace()
        }
        quanXian.baocun(editor)
        Myutil.settv(drawerBean.mname, TvMyName)
        Myutil.settv(drawerBean.youxiang, TvYouxiang)
        Myutil.settv(Myutil.getdata(drawerBean.daoqishijian), TvDaoqishijian)
        Myutil.settv(drawerBean.bieming, TvBieming)
        Myutil.settv(Myutil.getdata(drawerBean.shangcidenglu), TvShangcidenglu)
        Myutil.settv(Myutil.getdata(drawerBean.zhuceshijian), TvZhuceshijian)
        Myutil.settv(Myutil.getdata(drawerBean.denglushijian), TvDenglushijian)
    }

    /**
     * 初始化数据和加载布局
     */
    private fun initView() {
        isnotification()
        drawerLayout()

        tvTitle.text = "我的工作"
        var m : MainItemBeans = MainItemBeans()
        listItems = m.datas
        var adapter = MainItemAdapter(listItems, this)
        GvHomePage.adapter = adapter
        GvHomePage.onItemClickListener = this
        iv_header_right.setOnClickListener(this)
        LlGengxing.setOnClickListener(this)
        IvNotification.setOnClickListener(this)
        IvDownload.setOnClickListener(this)
        LlQuit.setOnClickListener(this)
        Tv_Fuwu.setOnClickListener(this)
        Tv_Yingsi.setOnClickListener(this)
    }

    /**
     * onClick方法，用于点击radiobutton是切换fragment
     *
     * @param view
     */
    override fun onClick(v: View) {
        when(v){
            iv_header_right -> {
                val intent = Intent(this@NewMainKActivity, DialogActivity::class.java)
                startActivityForResult(intent, 101)
            }
            LlGengxing -> UpdataInfo(this@NewMainKActivity, true, sp).show()
            IvNotification -> {
                isnotification()
                val intent1 = Intent(this@NewMainKActivity, NotificationActivity::class.java)
                startActivityForResult(intent1, 105)
            }
            IvDownload -> {
                val intent1 = Intent(this@NewMainKActivity, LingShi1Activity::class.java)
                startActivity(intent1)
            }
            LlQuit -> {
                val myAlerDialog = MyAlerDialog(this)
                myAlerDialog.start()
                myAlerDialog.setdata("确定退出登录吗？")
                myAlerDialog.setleft("确定") {
                    myAlerDialog.dismiss()
                    var updatedialog = Myutil.showupdatedialog(this@NewMainKActivity, "正在退出登录", true)
                    Httputil.setLogout(this@NewMainKActivity, object : OnUserDataInterface {
                        override fun onUserData(data: String) {
                            myAlerDialog.dismiss()
                            if (data.indexOf("true") != -1) {
                                Myutil.MyTost("退出登录状态成功")
                                editor.putBoolean("islogin", false)
                                editor.commit()
                                finish()
                            }
                        }

                        override fun onNot(throwable: String) {
                            myAlerDialog.dismiss()
                            if (updatedialog != null) {
                                updatedialog.dismiss()
                            }
                            Myutil.MyTost("网络访问失败")
                        }
                    });
                }
                myAlerDialog.setright("取消") { myAlerDialog.dismiss() }
                myAlerDialog.show()

            }
            Tv_Fuwu -> {
                val intent = Intent(this, XieyiActivity::class.java)
                intent.putExtra("code", 1)
                startActivity(intent)
            }
            Tv_Yingsi -> {
                val intent = Intent(this, XieyiActivity::class.java)
                intent.putExtra("code", 2)
                startActivity(intent)
            }
        }

    }

    override fun onItemClick(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
        val intent = Intent(this, HomeActivity::class.java)
        intent.putExtra("title", listItems[position].title)
        intent.putExtra("code", listItems[position].code)
        startActivity(intent)
    }



    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (data == null) {
            return
        }
        when (requestCode) {

            105 -> {
                isnotification()
            }

        }
    }


    override fun onKeyDown(keyCode: Int, event: KeyEvent): Boolean {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (sp.getBoolean("Sophix", false)) {
//                Log.d("SophixManager", "去安装补丁")
                SophixManager.getInstance().killProcessSafely();

            } else {
                if (isdrawerLayout) {
                    DlLeft.closeDrawers()
                } else {
                    finish()

                }
                return true
            }
        }
        return super.onKeyDown(keyCode, event)
    }

    companion object {
        /**
         * MainActivity是否启动
         */
        var uid = ""
        var name = ""
        /**专卖店账号 */
        var ZhuanMaiDianid = ""
        private val a = "MainActivity"
    }


}
